package jwt

import (
	"github.com/golang-jwt/jwt/v5"
	"time"
)

type AppClaims struct {
	UserID   uint64
	Username string
	jwt.RegisteredClaims
}

// GenerateToken 生成TOKEN
func GenerateToken(userID uint64, username string, secret string, expires time.Duration) (string, error) {
	claims := AppClaims{
		UserID:   userID,
		Username: username,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    "Admin",
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(expires * time.Hour)),
			NotBefore: jwt.NewNumericDate(time.Now()),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(secret))
}

// ParseToken 验证token
func ParseToken(tokenString string, secret string) (*AppClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &AppClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})
	if claims, ok := token.Claims.(*AppClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, err
}
